<template>
  <div class="scenicList-wrapper">
    <section class="app-container">
      <el-row class="inputform" v-if="configQueryWhere.length > 0">
        <query-from
          ref="queryfrom"
          :showQueryWhere="configQueryWhere"
          v-if="fromInfo.layoutitemlist !== undefined"
          :data="fromInfo.layoutitemlist[0].widgetForm"
        ></query-from>
      </el-row>
      <el-row class="inputform" style="margin-top: 10px;">
        <el-col :span="22">
          <el-button
            type="primary "
            size="small"
            @click="loadData(1)"
            icon="el-icon-search"
            >查询</el-button
          >
          <el-button
            @click="Resetfromdata()"
            size="small"
            icon="el-icon-refresh"
            >重置</el-button
          >
          <el-button
            type="primary "
            size="small"
            @click="addfrom"
            icon="el-icon-plus"
            >新增</el-button
          >
          <el-button
            type="primary "
            @click="exportExlce()"
            size="small"
            icon="el-icon-download"
            >导出</el-button
          >
          <el-button
            type="info"
            icon="el-icon-upload2"
            size="small"
            @click="handleImport"
          >导入</el-button>
          <el-button
            type="info"
            icon="el-icon-upload2"
            size="small"
            @click="auditReport"
          >审核情况</el-button>
          <el-button
            type="primary"
            size="small"
            @click="butfromreport()"
            v-if="isShowButReport"
            icon="el-icon-pie-chart"
            >报表统计</el-button
          >
        </el-col>
        <el-col :span="2" style="text-align: right;">
          <el-dropdown
            @command="handleCommand"
            trigger="click"
            style="margin-top: 10px;
    margin-bottom: auto;"
          >
            <span class="el-dropdown-link">
              <i class="el-icon-setting color3" style="font-size: 20px;" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="q">设置条件</el-dropdown-item>
              <el-dropdown-item command="c">设置列</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div class="ant-table_container">
        <a-table
          bordered
          :customRow="rowClick"
          :data-source="tableData"
          :columns="tableColumns"
          :pagination="false"
          :scroll="{ x: gridlistwidth }"
        >
          <div
            v-for="item in scopedSlots"
            v-bind:key="item.dataid"
            slot-scope="text, record"
            :slot="item.dataid"
          >
            <a
              v-if="item.type === 'datarelevance'"
              class="hreflink"
              @click="opendatarelevance(item, record, item.dataid)"
              >{{ text }}</a
            >
            <div
              v-else
              v-html="getcelvalue(item.type, record, text, item.dragType)"
            ></div>
          </div>
          <div slot="operation" slot-scope="text, record">
            <a
              class="margin-a"
              href="javascript:;"
              style="margin-right: 5px;"
              @click="viewfrom(record)"
              ><i class="el-icon-edit"></i>修改</a
            >
            <a
              class="margin-a"
              slot="reference"
              style="margin-right: 5px;"
              @click="deleteitem(record)"
              ><i class="el-icon-delete"></i>删除</a
            >
          </div>
        </a-table>
      </div>
      <div class="ant-table_footer">
        <a-pagination
          :loading="isloading"
          v-model="pagination.currnet"
          :default-current="1"
          :total="pagination.total"
          show-quick-jumper
          @change="handleTableChange"
          @showSizeChange="showSizeChange"
          :pageSize="pagination.pagesize"
          show-size-changer
        />
      </div>
    </section>
    <el-drawer
      title="设置列"
      :visible.sync="showConfigCel"
      :direction="direction"
      :size="'300px'"
    >
      <div class="querywhere">
        <el-checkbox-group v-model="configshowcel" size="small">
          <el-checkbox
            border
            v-for="(item, index) in allcels"
            :key="item.value + index"
            :label="item.value"
            >{{ item.label }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="primary" @click="saveShowCelNames">保存</el-button>
        <el-button type="info" @click="configshowcel = []">重置</el-button>
      </div>
    </el-drawer>
    <el-drawer
      title="设置查询条件"
      :visible.sync="showConfigQueryWhere"
      :direction="direction"
      :size="'300px'"
    >
      <div class="querywhere">
        <el-checkbox-group v-model="configQueryWhere" size="small">
          <el-checkbox
            border
            v-for="(item, index) in allcels"
            :key="item.value + index"
            :label="item.value"
            >{{ item.label }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="primary" @click="saveConfigQueryWhere">保存</el-button>
        <el-button type="info" @click="configQueryWhere = []">重置</el-button>
      </div>
    </el-drawer>
    <a-modal
      v-model="visible"
      wrapClassName="ant-modal-centered dialog is-portal-color window-max hiddenoverflow"
      width="100%"
      :zIndex="799"
      :footer="null"
      :bodyStyle="{ padding: '0px' }"
      :closable="false"
      :destroyOnClose="true"
    >
      <fromreport :fromInfo="fromInfo" @close="winclose"></fromreport>
    </a-modal>

    <fromdialog ref="reffromdialog" :dialogclose="dialogclose"> </fromdialog>
    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport +'&formId='+ this.fromid"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <BigImg :visible="photoVisible" :url="bigImgUrl" @closeClick="()=>{photoVisible=false}"></BigImg>
    <el-dialog :title="auditform.title" :visible.sync="auditform.open" width="600px" height="800px" append-to-body>
        <el-form ref="form" :model="auditform" label-width="80px">
          <el-row>
            <el-form-item label="审核备注" prop="nickName">
              <el-input v-model="auditform.auditremark"   type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" placeholder="审核备注" />
            </el-form-item>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAuditSuccess">审核通过</el-button>
        <el-button type="primary" @click="submitAuditFalier">审核不通过</el-button>
        <el-button @click="auditform.open= false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="审核情况" :visible.sync="auditReportOpen" width = "400px" height="400px" append-to-body>
      <el-table :data="auditReportList">
        <el-table-column label="审核状态" align="center" prop="auditStatus" />
        <el-table-column label="数量" align="center" prop="auditStatusCount" />
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import QueryFrom from '@/components/formdesign/queryFrom.vue'
import { getFromInfo, saveConfigQueryJson,importTemplate,auditOperator,getAuditReport } from '@/api/tappfrom.js'
import { saveConfigShowCelNames } from '@/api/packageInterface.js'
import { apiComm, ExportExlce } from '@/api/index'
import fromreport from '@/views/fromdesign/fromreport.vue'
import { getfromScopedSlots, getCotrlCelValue } from './fromCom.js'
import {getToken} from "@/utils/auth";
import BigImg from "@/components/BigImg";
export default {
  data() {
    return {
      auditform:{
        title: '信息审核',
        auditremark: '',
        $tableNewId: '',
        open: false,
        formid: this.fromid,
        questionName: '',
        record: undefined,
        auditflag: ''
      },
      auditReportOpen:false,
      auditReportList: [],
      photoVisible: false,
      bigImgUrl: undefined,
      queryparam: { fromname: '' },
      scopedSlots: [],
      apicode: '',
      fromInfo: null,
      fromcontrolList: [],
      tableData: [],
      pagination: {
        currnet: 1,
        pagesize: 10,
        total: 0
      },
      tableColumns: [],
      isloading: false,
      fromid: '',
      openfromid: '',
      showConfigCel: false,
      direction: 'rtl',
      configshowcel: [],
      allcels: [],
      showConfigQueryWhere: false,
      configQueryWhere: [],
      isShowButReport: false,
      visible: false,
      selectId: '',
      gridlistwidth: 2000,
      // 数据导入参数
      upload: {
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        formId: this.fromid,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/From/importData"
      }
    }
  },
  components: { QueryFrom, fromreport ,BigImg},
  methods: {
    viewfrom(row) {
      console.log(this.auditform);
      this.$refs.reffromdialog.opendialog(this.fromid, row.fid,this.auditform.questionName)
      // window.open(`/viewfrom?fromid=${this.fromid}&tablefid=${row.fid}`)
      // this.$router.push({
      //   path: `/Flow/viewfrom?fromid=${this.fromid}&tablefid=${row.fid}`
      // })
    },
    deleteitem(row) {
      this.$confirm('删除该记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiComm(this.$route.query.questionName + '.deleteInfo', {
          fid: row.fid
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('删除成功！')
            this.loadData()
          } else {
            this.$message.success('删除失败！')
          }
        })
      })
    },
    dialogclose(issave) {
      this.$refs.reffromdialog.clasedialog()
      if (issave) {
        this.loadData()
      }
    },
    addfrom() {
      this.$refs.reffromdialog.opendialog(this.fromid, '',this.auditform.questionName)
      // window.open(`/viewfrom?fromid=${this.fromid}`)
    },
    LoadQueryWhere() {
      if (this.fromInfo !== null) {
        this.loadData(1)
      } else {
        getFromInfo(this.fromid).then(res => {
          this.fromInfo = JSON.parse(res.data.fromdesignjson)
          this.configQueryWhere = []
          if (
            res.data.queryJson !== undefined &&
            res.data.queryJson !== null &&
            res.data.queryJson !== '' &&
            this.fromInfo !== undefined &&
            this.fromInfo.layoutitemlist !== undefined
          ) {
            this.configQueryWhere = res.data.queryJson.split(';')
          }
          let ctrlsobject = getfromScopedSlots(this.fromInfo)
          this.scopedSlots = ctrlsobject.scopedSlots
          this.isShowButReport = ctrlsobject.isShowButReport
          this.loadData(1)
        })
      }
    },
    loadData(pagenum) {
      if (this.isloading) {
        return
      }
      const param = this.getqueryparam()
      param.page = pagenum !== undefined ? pagenum : this.pagination.currentpage
      param.rows = this.pagination.pagesize
      this.isloading = true
      this.configshowcel = []
      this.allcels = []
      apiComm(this.apicode, param).then(res => {
        this.isloading = false
        if (res.code === 0 && res.success) {
          if (
            res.data.showCelNames !== null &&
            res.data.showCelNames !== undefined
          ) {
            this.configshowcel = res.data.showCelNames.split(';')
          }
          this.tableColumns = []
          this.tableColumns.push({
            title: '操作',
            dataIndex: 'operation',
            width: 150,
            scopedSlots: { customRender: 'operation' },
            align: 'center'
          })
          for (let i = 0; i < res.data.columns.length; i++) {
            this.allcels.push({
              label: res.data.columns[i].headname,
              value: res.data.columns[i].bindname
            })
            const item = {
              title: res.data.columns[i].headname,
              dataIndex: res.data.columns[i].bindname,
              align: 'center'
            }
            let scopeditem = this.scopedSlots.filter(
              ee => ee.dataid === res.data.columns[i].bindname
            )
            if (scopeditem.length > 0) {
              item.scopedSlots = {
                customRender: res.data.columns[i].bindname
              }
              scopeditem[0].fromId = res.data.columns[i].fromId
            }
            if (
              this.configshowcel.length === 0 ||
              this.configshowcel.indexOf(res.data.columns[i].bindname) >= 0
            ) {
              this.tableColumns.push(item)
            }
          }
          this.pagination.current = param.page
          this.pagination.total = res.totalcount
          this.tableData = res.data.list
          this.gridlistwidth = (this.tableColumns.length + 1) * 150
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    exportExlce() {
      const param = this.getqueryparam()
      ExportExlce(this.apicode, param).then(res => {
          return res;
      }).then(response=>{
        this.download(response.data);
      }).catch(function() {});
    },
    handleTableChange(pagination) {
      this.loadData(pagination)
    },
    showSizeChange(page, pageSize) {
      this.pagination.pagesize = pageSize
      this.loadData(1)
    },
    getcelvalue(type, record, text, dragType) {
      return getCotrlCelValue(type, record, text, dragType)
    },
    handleCommand(command) {
      switch (command) {
        case 'q':
          this.showConfigQueryWhere = true
          break
        case 'c':
          this.showConfigCel = true
          break
        default:
          break
      }
    },
    saveShowCelNames() {
      if (this.configshowcel.length === 0) {
        this.$message.error('请选择显示的列！')
      } else {
        saveConfigShowCelNames({
          callMethodCodeName: this.apicode,
          showCelNames: this.configshowcel.join(';')
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('设置成功！')
            this.loadData(1)
          }
        })
      }
    },
    saveConfigQueryWhere() {
      saveConfigQueryJson({
        fid: this.fromid,
        queryJson: this.configQueryWhere.join(';')
      }).then(res => {
        if (res.code === 0) {
          if (this.$refs.queryfrom !== undefined) {
            this.$refs.queryfrom.Resetfromdata()
          }
          this.showConfigQueryWhere = false
          this.$message.success('设置成功！')
          this.loadData(1)
        }
      })
    },
    getqueryparam() {
      if (this.$refs.queryfrom !== undefined) {
        return this.$refs.queryfrom.getfromdata()
      }
      return {}
    },
    Resetfromdata() {
      if (this.$refs.queryfrom !== undefined) {
        return this.$refs.queryfrom.Resetfromdata()
      }
    },
    butfromreport() {
      this.visible = true
    },
    winclose() {
      this.visible = false
    },
    opendatarelevance(item, row, dataid) {
      this.openfromid = item.fromId
      this.selectId = row[dataid.replace('_text', '')]
      this.$refs.reffromdialog.opendialog(this.openfromid, this.selectId,this.auditform.questionName)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      const param = this.getqueryparam()
      importTemplate(this.apicode, param).then(res => {
        this.download(res.data);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    showBigImage(imgUrl){
      if (imgUrl != "") {
        this.photoVisible = true;
        this.bigImgUrl = imgUrl;
      }
    },
    rowClick: function (record, index){
      return {
        on: {
          // click: () => {
          //   console.log('点击了我')
          // },
          dblclick: () => {
            // this.auditform.open = true;
            this.auditform.$tableNewId = record.fid;
            this.auditform.record = record;
            this.auditform.auditremark = record.auditremark;
            this.viewfrom(record);
          },
          // ...
        }
      }
    },
    submitAuditSuccess(){
      this.auditform.auditflag ="审核通过";
      auditOperator(this.auditform).then(res =>{
        this.auditform.record.auditflag = '审核通过'
        this.auditform.record.auditremark = this.auditform.auditremark;
        this.auditform.open = false;
        this.$message.success("审核操作成功");
      })
    },
    submitAuditFalier(){
      if(this.auditform.auditremark===''){
        this.$message.error('审核不通过时，审核备注不能为空')
        return;
      }
      auditOperator(this.auditform).then(res =>{
        this.auditform.record.auditflag = '审核失败'
        this.auditform.record.auditremark = this.auditform.auditremark;
        this.auditform.open = false;
        this.$message.success("审核操作成功");
      })
    },
    auditReport(){
      //统计审核情况
      getAuditReport(this.fromInfo).then(res =>{
        this.auditReportOpen=true;
        this.auditReportList=res.data;
      })
    }
  },
  computed: {},
  created() {
    this.fromid = this.$route.query.fromid
    this.auditform.formid = this.$route.query.fromid
    this.apicode = this.$route.query.questionName + '.querylist'
    this.auditform.questionName = this.$route.query.questionName;

    this.questionName = this.$route.query.questionName;
    this.LoadQueryWhere()
    let _this=this;
    window.showBigImage = this.showBigImage;
  }
}
</script>
<style scoped>
.el-checkbox.is-bordered.el-checkbox--small {
  margin-bottom: 10px;
}
.inputform div:first-child {
  height: 40px;
  margin-bottom: 10px;
}
.inputform button {
  margin-left: 5px;
  margin-right: 5x;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}
.querywhere {
  margin: 5px;
}
.querywhere >>> .el-checkbox.is-bordered.el-checkbox--small {
  padding: 8px;
  width: 122px;
}
.querywhere >>> .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0px;
}
.querywhere >>> .el-checkbox {
  margin-right: 10px;
}
.ant-table_container >>> .ant-table-tbody td {
  overflow: hidden; /*超出部分隐藏*/
  text-overflow: ellipsis; /* 超出部分显示省略号 */
  white-space: nowrap; /*规定段落中的文本不进行换行 */
}
.ant-table_container >>> .hreflink {
  text-decoration: underline;
  color: #409eff;
  cursor: pointer;
}
.ant-table_container >>> .hreflink:hover {
  text-decoration: underline;
  color: #409eff;
  cursor: pointer;
}
</style>
